$(function() {
	var Weibo;
	return window.Weibo = Weibo = (function() {

		function Weibo(access_token) {
			this.access_token = access_token;
			this.recent_w = new Object;
			this.weibos = [];
		}

		Weibo.prototype.search_weibos = function(buttonType,keyword,task,page,chooseWeibos,screenData) {
			$.ajaxSetup({
				beforeSend: function(xhr) {
					return xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
				}
			});
			var asy = true;
			if(buttonType=="fresh") asy=false;
			var stime, etime, pr ,ci,scr;
			if(buttonType=="screen"){
				stime = screenData.stime;
				etime = screenData.etime;
				pr = screenData.pr;
				ci = screenData.ci;
				scr=true;
			}

			return $.ajax({
				url: "s/search",
				type: "POST",
				async: asy,
				data: {
					'keyword': keyword,
					'task': task,
					'current_page': page,
					// 'sorttype': null,
					// 'msgtype': null,
					'search_type': $(".engine-toggle").attr('data'),
					'starttime': stime,
					'endtime': etime,
					'province': pr,
					'city': ci,
					'screen':scr
				},
				success: function(retval) {
					console.log("success search_weibos");
					console.log(retval);
					if(!retval.error){
						if(buttonType=="search" || buttonType == "screen") {//点击搜索
							$.waitState(false,"搜 索",$(".search-btn"));
							$.waitState(false,"筛 选",$(".screen-r input"));
							$(".microblog-list").html("");
							$('.chooseNum').html(0);
							$("#choosePage").show();
							var obj={
								task:retval.task,
								flowy_token:$.cookie("flowy_token"),
								page:retval.current_page,
								key:keyword,
								weibos : [],
								push_weibos:{successful:[],failed:[]},
								push_comment:null
							};
							$(window).scrollTo($('.screen'), 500);
							window.localStorage.setItem("searchInfo",JSON.stringify(obj));//存储信息至本地
							window.weibo_count=0;
							if(retval.weibos.is_finish) $.waitState(true,"显示更多",$(".more"));
						}
						else if(buttonType == "fresh"){//再次进入
							$('.search input').val(keyword);
						}
						else if(buttonType == "more"){
							$.waitState(false,"显示更多",$(".more"));
						}

						//如果返回0条数据
						if(retval.weibos.length == 0){
							$('BODY').f_popup({content:"无更多数据！"});
						}else{
							$(".check-all input").removeClass("checked").prop("checked",false);
							append(retval.weibos, page,keyword);
						}
						console.log(jQuery.parseJSON(window.localStorage.getItem("searchInfo")));
					}
					else{
						$.waitState(false,"显示更多",$(".more"));
						$.waitState(false,"搜 索",$(".search-btn"));
						$.waitState(false,"筛 选",$(".screen-r input"));
						$('BODY').f_popup({content:retval.msg.content});
					}
				},
				error: function(retval) {
					$.waitState(false,"显示更多",$(".more"));
					$.waitState(false,"搜 索",$(".search-btn"));
					$.waitState(false,"筛 选",$(".screen-r input"));
					console.log("error search_weibos");
					console.log(retval);
					$('BODY').f_popup({content:"系统繁忙，请稍后重试！"});
				}
			});
		};

		function append (weibos,page,key) {
			for(var i=0; i<weibos.length; i++){
				var ind=window.weibo_count+i;
				var weiboid={
					mid:weibos[i].id,
					uid:weibos[i].user.id,
					from:1,index:ind};
				var li = $("<li />").data("id", weiboid).addClass("available");
				if(ind%2==0){
					li.css({"margin":0});
				}
				var info = '<span class="microblog-panel-top"><input type="checkbox"/>' +
				'<span class="header"><img src="'+weibos[i].user.profile_image_url+'" alt=""></span>'+
				'<span class="username"><strong>'+weibos[i].user.screen_name+'</strong></span>'+
				'<span class="gender">'+$.getGender(weibos[i].user.gender)+'</span>'+
				'<span class="location">'+weibos[i].user.location+'</span></span>';
				var pic=weibos[i].bmiddle_pic;
				var picSpan=""
				if(pic&&pic!="")
					picSpan='<span class="img"><img src="'+pic+'" alt=""></span>';
				var message = '<span class="microblog-panel-bottom"><span class="microblog-content">' +
				'<span class="microblog-text">'+$.matchStrs($.subStr(weibos[i].text,90),key)+'</span><span class="date-time">' +
				$.formatTime(new Date(weibos[i].created_at),'yyyy-MM-dd hh:mm') +'</span></span>'+picSpan+'</span>';

				li.append(info + message);
				$(".microblog-list").append(li);
			}
			window.weibo_count+=weibos.length;
		};

		Weibo.prototype.comment_weibos = function(task,weibo_ids,pushinfo) {
			var _this = this;

			// var regPattern = "(?:([A-Za-z]+):[/]{2})(?:[0-9A-Za-z-]+([.][0-9A-Za-z-]+)+)(?::([0-9]{1,5}))?(?:[/][/0-9A-Za-z_!~*\'().;?:@&=+$,%#-]*)?";
			// var regex = new RegExp(regPattern, 'g');
			// var urls = pushinfo.match(regex) || [];
			// $.each(urls, function(index, value) {
			// 	pushinfo = pushinfo.replace(value, '[url_' + index + ']')
			// });

			var sto=jQuery.parseJSON(window.localStorage.getItem("searchInfo"));
			var successful=sto.push_weibos.successful,failed=sto.push_weibos.failed;
			var error=sto.push_weibos.error;
			for(var i=0; i<weibo_ids.length; i++){
				var thisLi = $.searchInArray(weibo_ids[i]["mid"],sto.weibos,"mid");
				var index = sto.weibos[thisLi].index;
				var li=$(".microblog-list li:eq("+sto.weibos[thisLi].index+")");
				li.removeClass("available").addClass("unable");
				li.find(".microblog-panel-top input").replaceWith('<span class="send-succeed">已发送</span>');
				successful.push(sto.weibos[thisLi]);
			};

			return $.ajax({
				url: "s",
				type: "POST",
				data: {
					'comment': pushinfo,
					'weibos': weibo_ids ,
					'task':task
				},
				success: function(retval) {
					$.waitState(false,"推送",$(".push-btn"));
					console.log("success comment_weibos");
					console.log(retval);
					$('BODY').f_popup({content:"您已成功发送！"});
					// if(retval.failed.length==0)
					//alert_content = "您已成功发送"+retval.successful.length+"条微博！";
					// else if(retval.successful.length==0)
					// 	alert_content = "发送失败"+retval.failed.length+"条微博！";
					// else
					// 	alert_content = "您已成功发送"+retval.successful.length+"条,失败"+retval.failed.length+"条!";
					//     $('BODY').f_popup({content:alert_content});

					// var sto=jQuery.parseJSON(window.localStorage.getItem("searchInfo"));
					// var successful=sto.push_weibos.successful,failed=sto.push_weibos.failed;
					// var error=sto.push_weibos.error;
					// for(var i=0; i<retval.successful.length; i++){
					// 	for(var key in retval.successful[i]){
					// 		var thisLi = $.searchInArray(key,sto.weibos,"mid");
					// 		var index = sto.weibos[thisLi].index;
					// 		var li=$(".microblog-list li:eq("+sto.weibos[thisLi].index+")");
					// 		li.removeClass("available").addClass("unable");
					// 		li.find(".microblog-panel-top input").replaceWith('<span class="send-succeed">已发送</span>');
					// 		successful.push(sto.weibos[thisLi]);
					// 	}
					// }

					// for(var i=0; i<retval.failed.length; i++){
					// 	for(var key in retval.failed[i]){
					// 		var thisLi = $.searchInArray(key,sto.weibos,"mid");
					// 		var index = sto.weibos[thisLi].index;
					// 		var li = $(".microblog-list li:eq("+sto.weibos[thisLi].index+")");
					// 		li.removeClass("available").addClass("unable");
					// 		li.find(".microblog-panel-top input").replaceWith('<span class="send-failed">发送失败</span>');
					// 		failed.push(sto.weibos[thisLi]);
					// 	}
					// }

					sto.push_weibos={"successful":successful,"failed":failed,"error":error};
					$(".chooseNum").html(0);
					sto.weibos=[];
					window.localStorage.setItem("searchInfo",JSON.stringify(sto));
				},
				error: function(retval) {
					$('BODY').f_popup({content:"系统繁忙，请稍后重试！"});
					$.waitState(false,"推送",$(".push-btn"));
					console.log("error comment_weibos");
					return console.log(retval);
				}
			});
		};
		return Weibo;
	})();
});